#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_USERS 100
#define MAX_BOOKS 1000
#define MAX_NAME_LEN 50
#define MAX_TITLE_LEN 100
#define MAX_AUTHOR_LEN 50
#define MAX_USERNAME_LEN 20
#define MAX_PASSWORD_LEN 20

// 用户角色枚举
typedef enum {
    ROLE_STUDENT,
    ROLE_ADMIN
} UserRole;

// 用户结构体
typedef struct {
    char username[MAX_USERNAME_LEN];
    char password[MAX_PASSWORD_LEN];
    UserRole role;
} User;

// 图书结构体
typedef struct {
    int id;
    char title[MAX_TITLE_LEN];
    char author[MAX_AUTHOR_LEN];
    int year;
    int is_borrowed;
} Book;

// 全局变量
User users[MAX_USERS];
int userCount = 0;

Book books[MAX_BOOKS];
int bookCount = 0;

int currentUserIndex = -1; // -1表示未登录

// 函数声明
void initSystem();
void mainMenu();
void registerUser();
void login();
void adminMenu();
void studentMenu();
void addBook();
void deleteBook();
void modifyBook();
void searchBooks();
void exactSearch();
void fuzzySearch();
void displayAllBooks();
void logout();
void saveData();
void loadData();

int main1() {
    initSystem();
    loadData();
    mainMenu();
    saveData();
    return 0;
}

// 初始化系统
void initSystem() {
    // 添加默认管理员账户
    strcpy(users[userCount].username, "admin");
    strcpy(users[userCount].password, "admin123");
    users[userCount].role = ROLE_ADMIN;
    userCount++;
}

// 主菜单
void mainMenu() {
    int choice;
    do {
        printf("\n===== 图书管理系统 =====\n");
        printf("1. 注册\n");
        printf("2. 登录\n");
        printf("3. 退出系统\n");
        printf("请选择操作: ");
        scanf("%d", &choice);
        while (getchar() != '\n'); // 清除输入缓冲区

        switch (choice) {
            case 1:
                registerUser();
                break;
            case 2:
                login();
                break;
            case 3:
                printf("感谢使用图书管理系统，再见！\n");
                break;
            default:
                printf("无效选择，请重新输入！\n");
        }
    } while (choice != 3);
}

// 用户注册
void registerUser() {
    if (userCount >= MAX_USERS) {
        printf("用户数量已达上限，无法注册新用户！\n");
        return;
    }

    char username[MAX_USERNAME_LEN];
    char password[MAX_PASSWORD_LEN];
    int roleChoice;

    printf("\n----- 用户注册 -----\n");
    printf("请输入用户名: ");
    scanf("%s", username);

    // 检查用户名是否已存在
    for (int i = 0; i < userCount; i++) {
        if (strcmp(users[i].username, username) == 0) {
            printf("用户名已存在，请选择其他用户名！\n");
            return;
        }
    }

    printf("请输入密码: ");
    scanf("%s", password);

    printf("请选择角色 (0-学生, 1-管理员): ");
    scanf("%d", &roleChoice);

    if (roleChoice != 0 && roleChoice != 1) {
        printf("无效的角色选择！\n");
        return;
    }

    // 保存用户信息
    strcpy(users[userCount].username, username);
    strcpy(users[userCount].password, password);
    users[userCount].role = (roleChoice == 0) ? ROLE_STUDENT : ROLE_ADMIN;
    userCount++;

    printf("注册成功！\n");
}

// 用户登录
void login() {
    char username[MAX_USERNAME_LEN];
    char password[MAX_PASSWORD_LEN];
    int found = 0;

    printf("\n----- 用户登录 -----\n");
    printf("请输入用户名: ");
    scanf("%s", username);
    printf("请输入密码: ");
    scanf("%s", password);

    for (int i = 0; i < userCount; i++) {
        if (strcmp(users[i].username, username) == 0 &&
            strcmp(users[i].password, password) == 0) {
            currentUserIndex = i;
            found = 1;
            break;
        }
    }

    if (found) {
        printf("登录成功！欢迎 %s\n", users[currentUserIndex].username);
        if (users[currentUserIndex].role == ROLE_ADMIN) {
            adminMenu();
        } else {
            studentMenu();
        }
    } else {
        printf("用户名或密码错误！\n");
    }
}

// 管理员菜单
void adminMenu() {
    int choice;
    do {
        printf("\n===== 管理员菜单 =====\n");
        printf("1. 添加图书\n");
        printf("2. 删除图书\n");
        printf("3. 修改图书信息\n");
        printf("4. 查询图书\n");
        printf("5. 显示所有图书\n");
        printf("6. 退出登录\n");
        printf("请选择操作: ");
        scanf("%d", &choice);
        while (getchar() != '\n'); // 清除输入缓冲区

        switch (choice) {
            case 1:
                addBook();
                break;
            case 2:
                deleteBook();
                break;
            case 3:
                modifyBook();
                break;
            case 4:
                searchBooks();
                break;
            case 5:
                displayAllBooks();
                break;
            case 6:
                logout();
                break;
            default:
                printf("无效选择，请重新输入！\n");
        }
    } while (choice != 6);
}

// 学生菜单
void studentMenu() {
    int choice;
    do {
        printf("\n===== 学生菜单 =====\n");
        printf("1. 查询图书\n");
        printf("2. 显示所有图书\n");
        printf("3. 退出登录\n");
        printf("请选择操作: ");
        scanf("%d", &choice);
        while (getchar() != '\n'); // 清除输入缓冲区

        switch (choice) {
            case 1:
                searchBooks();
                break;
            case 2:
                displayAllBooks();
                break;
            case 3:
                logout();
                break;
            default:
                printf("无效选择，请重新输入！\n");
        }
    } while (choice != 3);
}

// 添加图书
void addBook() {
    if (bookCount >= MAX_BOOKS) {
        printf("图书数量已达上限，无法添加新图书！\n");
        return;
    }

    printf("\n----- 添加图书 -----\n");
    printf("请输入图书标题: ");
    fgets(books[bookCount].title, MAX_TITLE_LEN, stdin);
    books[bookCount].title[strcspn(books[bookCount].title, "\n")] = 0; // 去除换行符

    printf("请输入作者: ");
    fgets(books[bookCount].author, MAX_AUTHOR_LEN, stdin);
    books[bookCount].author[strcspn(books[bookCount].author, "\n")] = 0;

    printf("请输入出版年份: ");
    scanf("%d", &books[bookCount].year);

    books[bookCount].id = bookCount + 1;
    books[bookCount].is_borrowed = 0;

    bookCount++;
    printf("图书添加成功！\n");
}

// 删除图书
void deleteBook() {
    int id;
    printf("\n----- 删除图书 -----\n");
    printf("请输入要删除的图书ID: ");
    scanf("%d", &id);

    int found = 0;
    for (int i = 0; i < bookCount; i++) {
        if (books[i].id == id) {
            found = 1;
            // 将后面的图书前移
            for (int j = i; j < bookCount - 1; j++) {
                books[j] = books[j + 1];
            }
            bookCount--;
            printf("图书删除成功！\n");
            break;
        }
    }

    if (!found) {
        printf("未找到ID为 %d 的图书！\n", id);
    }
}

// 修改图书信息
void modifyBook() {
    int id;
    printf("\n----- 修改图书信息 -----\n");
    printf("请输入要修改的图书ID: ");
    scanf("%d", &id);
    while (getchar() != '\n'); // 清除输入缓冲区

    int found = 0;
    for (int i = 0; i < bookCount; i++) {
        if (books[i].id == id) {
            found = 1;

            printf("当前标题: %s\n", books[i].title);
            printf("请输入新标题 (直接回车保持不变): ");
            char newTitle[MAX_TITLE_LEN];
            fgets(newTitle, MAX_TITLE_LEN, stdin);
            newTitle[strcspn(newTitle, "\n")] = 0;
            if (strlen(newTitle) > 0) {
                strcpy(books[i].title, newTitle);
            }

            printf("当前作者: %s\n", books[i].author);
            printf("请输入新作者 (直接回车保持不变): ");
            char newAuthor[MAX_AUTHOR_LEN];
            fgets(newAuthor, MAX_AUTHOR_LEN, stdin);
            newAuthor[strcspn(newAuthor, "\n")] = 0;
            if (strlen(newAuthor) > 0) {
                strcpy(books[i].author, newAuthor);
            }

            printf("当前出版年份: %d\n", books[i].year);
            printf("请输入新出版年份 (输入0保持不变): ");
            int newYear;
            scanf("%d", &newYear);
            if (newYear != 0) {
                books[i].year = newYear;
            }

            printf("图书信息修改成功！\n");
            break;
        }
    }

    if (!found) {
        printf("未找到ID为 %d 的图书！\n", id);
    }
}

// 查询图书菜单
void searchBooks() {
    int choice;
    do {
        printf("\n----- 查询图书 -----\n");
        printf("1. 精确查询\n");
        printf("2. 模糊查询\n");
        printf("3. 返回上级菜单\n");
        printf("请选择查询方式: ");
        scanf("%d", &choice);
        while (getchar() != '\n'); // 清除输入缓冲区

        switch (choice) {
            case 1:
                exactSearch();
                break;
            case 2:
                fuzzySearch();
                break;
            case 3:
                return;
            default:
                printf("无效选择，请重新输入！\n");
        }
    } while (choice != 3);
}

// 精确查询
void exactSearch() {
    char keyword[MAX_TITLE_LEN];
    int found = 0;

    printf("\n----- 精确查询 -----\n");
    printf("请输入图书标题或作者: ");
    fgets(keyword, MAX_TITLE_LEN, stdin);
    keyword[strcspn(keyword, "\n")] = 0;

    printf("\n查询结果:\n");
    printf("ID\t标题\t\t作者\t\t年份\t借阅状态\n");
    printf("------------------------------------------------------------\n");

    for (int i = 0; i < bookCount; i++) {
        if (strcmp(books[i].title, keyword) == 0 ||
            strcmp(books[i].author, keyword) == 0) {
            printf("%d\t%s\t\t%s\t\t%d\t%s\n",
                   books[i].id,
                   books[i].title,
                   books[i].author,
                   books[i].year,
                   books[i].is_borrowed ? "已借出" : "可借阅");
            found = 1;
        }
    }

    if (!found) {
        printf("未找到匹配的图书！\n");
    }
}

// 模糊查询
void fuzzySearch() {
    char keyword[MAX_TITLE_LEN];
    int found = 0;

    printf("\n----- 模糊查询 -----\n");
    printf("请输入关键词: ");
    fgets(keyword, MAX_TITLE_LEN, stdin);
    keyword[strcspn(keyword, "\n")] = 0;

    // 将关键词转换为小写以便不区分大小写搜索
    char lowerKeyword[MAX_TITLE_LEN];
    strcpy(lowerKeyword, keyword);
    for (int i = 0; lowerKeyword[i]; i++) {
        lowerKeyword[i] = tolower(lowerKeyword[i]);
    }

    printf("\n查询结果:\n");
    printf("ID\t标题\t\t作者\t\t年份\t借阅状态\n");
    printf("------------------------------------------------------------\n");

    for (int i = 0; i < bookCount; i++) {
        char lowerTitle[MAX_TITLE_LEN];
        char lowerAuthor[MAX_AUTHOR_LEN];

        strcpy(lowerTitle, books[i].title);
        for (int j = 0; lowerTitle[j]; j++) {
            lowerTitle[j] = tolower(lowerTitle[j]);
        }

        strcpy(lowerAuthor, books[i].author);
        for (int j = 0; lowerAuthor[j]; j++) {
            lowerAuthor[j] = tolower(lowerAuthor[j]);
        }

        if (strstr(lowerTitle, lowerKeyword) != NULL ||
            strstr(lowerAuthor, lowerKeyword) != NULL) {
            printf("%d\t%s\t\t%s\t\t%d\t%s\n",
                   books[i].id,
                   books[i].title,
                   books[i].author,
                   books[i].year,
                   books[i].is_borrowed ? "已借出" : "可借阅");
            found = 1;
        }
    }

    if (!found) {
        printf("未找到匹配的图书！\n");
    }
}

// 显示所有图书
void displayAllBooks() {
    printf("\n----- 所有图书 -----\n");
    if (bookCount == 0) {
        printf("图书馆暂无图书！\n");
        return;
    }

    printf("ID\t标题\t\t作者\t\t年份\t借阅状态\n");
    printf("------------------------------------------------------------\n");

    for (int i = 0; i < bookCount; i++) {
        printf("%d\t%s\t\t%s\t\t%d\t%s\n",
               books[i].id,
               books[i].title,
               books[i].author,
               books[i].year,
               books[i].is_borrowed ? "已借出" : "可借阅");
    }
}

// 退出登录
void logout() {
    currentUserIndex = -1;
    printf("已成功退出登录！\n");
}

// 保存数据到文件
void saveData() {
    FILE *userFile = fopen("users.dat", "wb");
    if (userFile) {
        fwrite(&userCount, sizeof(int), 1, userFile);
        fwrite(users, sizeof(User), userCount, userFile);
        fclose(userFile);
    }

    FILE *bookFile = fopen("books.dat", "wb");
    if (bookFile) {
        fwrite(&bookCount, sizeof(int), 1, bookFile);
        fwrite(books, sizeof(Book), bookCount, bookFile);
        fclose(bookFile);
    }
}

// 从文件加载数据
void loadData() {
    FILE *userFile = fopen("users.dat", "rb");
    if (userFile) {
        fread(&userCount, sizeof(int), 1, userFile);
        fread(users, sizeof(User), userCount, userFile);
        fclose(userFile);
    }

    FILE *bookFile = fopen("books.dat", "rb");
    if (bookFile) {
        fread(&bookCount, sizeof(int), 1, bookFile);
        fread(books, sizeof(Book), bookCount, bookFile);
        fclose(bookFile);
    }
}